<template>
  <div>
    <el-dialog title="客户导入" :visible.sync="batchImportVisible" width="500px" append-to-body>

      <el-form v-if="batchImportVisible" :model="importForm"  ref="importForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
        <el-form-item label="选择文件" prop="file" :rules="[{ required: true, message: '请选择文件', trigger: 'blur' }]">
          <OssUploadFileButton  :limit="1" :fileType="fileType" :fileSize="5120" :isShowUploadImg="true"
          ref="imgUploadRef" @input="uploadImg" :isShowBtn="true"></OssUploadFileButton>

        </el-form-item>
        <el-form-item label="学年学期" prop="type" :rules="[{ required: true, message: '请选择学年学期', trigger: 'blur' }]">
          <el-select v-model="importForm.studyId" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in studyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学员课程" prop="type">
           <el-radio-group v-model="importForm.type"  >
            <el-radio :label="0">课程不同</el-radio>
            <el-radio :label="1">课程相同</el-radio>
          </el-radio-group>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dataFormSubmit()">立即导入</el-button>
        <el-button type="primary" @click="downLoadTemplate()">模版下载</el-button>
        <el-button @click="closeImport()">取消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="课程详情" :visible.sync="addOrUpdateVisible" :with-header="false" size="650px">
      <div class="right-container">
        <div class="container-header">
          <div style="font-size: 14px">详情查看</div>
          <div @click="handleClose">
            <i class="el-icon-close" style="font-size: 18px"></i>
          </div>
        </div>
        <div class="container-content background-color-grey padding-10">
          <div class="bg-white border-radius">
            <div class="flex justify-between align-center margin-bottom-sm padding-lg border-bottom card-heard-title ">
              <div>
                <i class="el-icon-collection-tag" style="font-size: 18px"></i>
                个人信息
              </div>
            </div>
            <div class="padding-lg flex " >
              <div class="flex-1">姓名：{{classOrder.userName}}</div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">电话：{{classOrder.userPhone}}</div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">性别：{{classOrder.userSex}}</div>
            </div>
            <div class="padding-lg flex ">
              <div class="flex-1">编号：{{classOrder.isCode}}</div>
            </div>
          </div>
        </div>
      </div>

    </el-drawer>
    <div class="mod-user">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">

        <el-form-item label="姓名:">
          <el-input class="selectWidth" v-model="dataForm.username" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话:">
          <el-input class="selectWidth" v-model="dataForm.phone" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
          <el-button @click="exportDataList()">导出</el-button>
        </el-form-item>
      </el-form>
      <div class="margin-bottom-sm">
        <el-button type="primary" size="mini" @click="batchImport()">批量导入</el-button>
      </div>
      <el-table
        ref="orderListTableRef"
        :header-cell-style="tableHeaderStyle"
        :data="dataList" :height="height"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="userName"
          header-align="center"
          align="center"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="userPhone"
          header-align="center"
          align="center"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="userSex"
          header-align="center"
          align="center"
          label="性别">
        </el-table-column>
        <el-table-column
          prop="isCode"
          header-align="center"
          align="center"
          label="编号">
        </el-table-column>

        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button  type="text" size="small" @click="addOrUpdateHandle(scope.row.userId)">查看</el-button>
<!--            <el-button  type="text" size="small" @click="deleteHandle(scope.row.userId)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { values } from 'lodash';
import OssUploadFileButton from '../oss/oss-upload-file-button.vue';
import { saveAs } from 'file-saver';
export default {
  data () {
    return {
      fileList:[],
      batchImportVisible: false,
      importForm:{
        type: 1,
        url: '',
        studyId: ''
      },
      studyOptions: [
        {
          value: '',
          label: '请选择'
        },
      ],
      height: 0,
      dataForm: {
        year: '',
        orderCode: '',
        userName: '',
        userPhone: '',
        paymentStatus: ''
      },
      options: [{
        value: '2',
        label: '已支付'
      }, {
        value: '0',
        label: '支付中'
      }],
      orderDate:'',
      tableHeaderStyle: { background: '#f5f7fa !important', height: '20px !important', padding: '4px !important' },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      classOrder: {
        name: ''
      },
      fileType:[ 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']//excel文件类型
    }
  },
  components: {
    OssUploadFileButton
  },
  activated () {
    this.getstudyOptionsList()
    this.getDataList()
  },
  mounted() {
    console.log(document.body.clientHeight)
    // 至于减去多少，这个要看你的页面高度和你想将滚动轴固定在哪里了，数值可以更换
    this.$nextTick(() => {
      let tableHeight = document.body.clientHeight - 305
      this.height = tableHeight
    })
  },
  methods: {
    closeImport(){
      this.batchImportVisible = false;
      this.fileList = []
      this.importForm = {type: 1, url: '', studyId: ''}
    },
    dataFormSubmit(){
      console.log(this.importForm)
      //验证必填
      if (!this.importForm.url) {
        this.$message.error('请上传文件')
        return
      }
      if (!this.importForm.studyId) {
        this.$message.error('学年学期不能为空')
        return
      }
      this.$http({
        url: this.$http.adornUrl('/sys/userToken/readUser'),
        method: 'post',
        data: this.$http.adornData({
          'studyId': this.importForm.studyId,
          'url': this.importForm.url,
          'type': this.importForm.type
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success('导入成功')
          this.closeImport()
        }
      })
    },
    downLoadTemplate(){
        //https://image.cnslpa.com/%E4%BA%BA%E5%91%98%E5%88%97%E8%A1%A8.xlsx
        //浏览器直接访问这个链接

        this.$http({
        url: this.$http.adornUrl('/sys/userToken/downExcelUser'),
        method: 'get',
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        if (data && data.code === 0) {
          window.open(data.map.url);
        }
      });
    },
    uploadImg(data){
      console.log("上传后的数据", data)
      this.fileList = [];
      this.fileList.push({
        name: data.name,
        url: data.url
      })
      this.importForm.url = data.url
    },

    //获取学期学年数据
    getstudyOptionsList() {
      this.$http({
        url: this.$http.adornUrl('/class/study/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 9999999
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.page.list && data.page.list.length > 0) {
            for (let i = 0; i < data.page.list.length; i++) {
              this.studyOptions.push({
                value: data.page.list[i].id,
                label: data.page.list[i].name
              })
            }
          }
        }
      })
    },
    batchImport() {
      this.batchImportVisible = true

    },
    handleClose() {
      this.addOrUpdateVisible = false; // 关闭外层 Drawer 时不关闭内层 Drawer
    },
    repairTableByRef(refName) {
      this.$refs[refName].doLayout()
    },
    exportDataList () {
      let searchParams = {
        ...this.dataForm,
        ids: this.dataListSelections.map(item => item.userId).join(','),
        page: this.pageIndex,
        limit: this.pageSize,
      }
      this.$http.exportFile('/sys/userToken/exportList',  searchParams)
        .then(async (res)  => {
          console.log(res);
          let blob = new Blob([res])
          saveAs(blob, "用户列表.xlsx")
        }).catch(error => { console.error('文件导出失败:', error) })
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true

      var params={
        ...this.dataForm,
        page: this.pageIndex,
        limit: this.pageSize
      }
      this.$http({
        url: this.$http.adornUrl('/sys/userToken/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
        this.repairTableByRef('orderListTableRef')
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      console.log(val)
      this.dataListSelections = val
    },
    deleteHandle(id){
      var ids= id.split(',');
      this.$confirm(`确定要进行删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/userToken/delete'),
          method: 'post',
          data: this.$http.adornData({
            'ids':ids
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$http({
        url: this.$http.adornUrl(`/sys/userToken/info/${id}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.classOrder=data.user;
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 删除
    deleteHandle (id) {
      var userIds = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      this.$confirm(`确定进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/class/study/delete'),
          method: 'post',
          data: this.$http.adornData(userIds, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {})
    }
  }
}
</script>
<style>
.right-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.container-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px
}
</style>
